<template>
  <div class="role-with-permit-container">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-button type="text">员工姓名/电话</el-button>
      <el-input
          v-model="searchForm.staffInfo"
          placeholder="请输入员工姓名/电话"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
      />
      <el-button type="text">门店名称</el-button>
      <el-input
          v-model="searchForm.storeName"
          placeholder="请输入门店名称"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
    </div>

    <!-- 员工列表 -->
    <el-table
        :data="staffList"
        border
        stripe
        style="width: 100%; margin-top: 16px"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="staffAccount" label="员工账号" width="140" />
      <el-table-column prop="staffName" label="员工姓名" width="120" />
      <el-table-column prop="phone" label="员工电话" width="140" />
      <el-table-column prop="role.roleName" label="员工角色" width="120" />
      <el-table-column prop="storeDto.storeName" label="门店名称" width="160" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
              type="text"
              @click="handleEditPermission(scope.row)"
              text-color="#409EFF"
          >
            修改角色权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 角色权限编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="选择角色权限"
        :width="650"
        :before-close="handleDialogClose"
    >
      <div class="permission-dialog-content">
        <el-form ref="permissionForm" :model="formData" label-width="90px">
          <!-- 角色选择 -->
          <el-form-item label="选择角色" required>
            <el-select
                v-model="formData.roleId"
                placeholder="请选择角色"
                @change="loadRolePermissions(formData.roleId)"
                clearable
            >
              <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.roleName"
                  :value="role.id"
              />
            </el-select>
          </el-form-item>

          <!-- 权限列表 - 树形结构 -->
          <el-form-item label="权限设置">
            <div v-if="allPermissionList.length > 0" class="permission-tree">
              <el-tree
                  ref="permissionTree"
                  :data="allPermissionList"
                  show-checkbox
                  node-key="id"
                  :default-expand-all="true"
                  :default-checked-keys="checkedKeys"
                  :props="treeProps"
                  @check-change="handleCheckChange"
                  class="permission-tree"
              />
            </div>
            <div v-else class="empty-state">
              <el-empty description="暂无可用权限数据" />
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="savePermissionSetting">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import axios from "axios";

// 搜索表单数据
const searchForm = reactive({
  staffInfo: '',  // 员工姓名/电话搜索
  storeName: ''   // 门店名称搜索
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 员工列表数据
const staffList = ref([
  {
    "id": 1,
    "staffAccount": "admin001",
    "staffName": "李店长",
    "phone": "13811111111",
    "roleId": 4,
    "role": {
      "id": 4,
      "roleName": "店长",
      "description": "管理门店所有事务"
    },
    "storeId": 1,
    "storeDto": {
      "storeId": 1,
      "storeName": "极速汽车服务中心"
    }
  }
]);

// 弹窗状态
const dialogVisible = ref(false);



// 表单数据
const formData = reactive({
  staffId: null,       // 当前编辑的员工ID
  roleId: null,        // 选中的角色ID
  permissionIds: []    // 选中的权限ID数组
});

// 角色和权限数据
const roleList = ref([
  {
    "id": 1,
    "roleName": "系统管理员",
    "description": "拥有系统所有权限"
  }
]);

// 所有权限数据(树形结构)
const allPermissionList = ref([]);
// 树形结构配置
const treeProps = {
  children: 'children',
  label: 'permissionName'
};
const checkedKeys = ref([]);
const currentStaff = ref(null);

// 模拟API请求函数 - 实际项目中替换为真实接口调用
const getStaffList = () => {
  axios.post(`/carcenter-service-personnel/staff/getStaffListWithSearchDto`, searchForm)
      .then(resp => {
        staffList.value = resp.data.data;
        pagination.total = resp.data.data.length;
      });
};

const getRoles = () => {
  axios.get(`/carcenter-service-personnel/roles/getRoleList`)
      .then(resp => {
        roleList.value = resp.data.data;
      });
};

// 获取所有权限(树形结构)
const getAllPermissions = () => {
  return axios.get(`/carcenter-service-personnel/permissions/getAllpermissions`)
      .then(resp => {
        allPermissionList.value = resp.data.data;
        return resp.data.data;
      });
};

// 根据角色ID获取已拥有的权限
const getRolePermissions = (roleId) => {
  return axios.get(`/carcenter-service-personnel/permissions/getPermissionsByRoleId/${roleId}`)
      .then(resp => {
        // 提取权限ID数组
        return resp.data.data.map(perm => perm.id);
      });
};

const modifyPermissionByRoleId = (roleId, permissionIds) => {
  axios.put(`/carcenter-service-personnel/role-permissions/modifyPermissionsWithRoleId/${roleId}`, permissionIds)
      .then(resp => {
        ElMessage.success(resp.data.message);
      })
      .catch(err => {
        ElMessage.error(err.response.data);
      });
};

const saveRole = (data) => {
  return axios.put(`/carcenter-service-personnel/staff/modifyRoleByStaffId/${data.staffId}/${data.roleId}`)
      .then(resp => {
        ElMessage.success(resp.data.message);
        return resp.data.code === 200;
      })
      .catch(err => {
        ElMessage.error(err.response.data);
        return false;
      });
};

// 初始化组件
onMounted(async () => {
  // 加载角色列表
  await getRoles();
  // 加载所有权限(树形结构)
  await getAllPermissions();
  // 加载员工列表
  getStaffList();
});

// 搜索按钮点击
const handleSearch = () => {
  pagination.currentPage = 1;
  getStaffList();
};

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  getStaffList();
};

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getStaffList();
};

// 打开编辑弹窗
const handleEditPermission = (staff) => {
  currentStaff.value = staff;
  formData.staffId = staff.id;
  formData.roleId = staff.roleId; // 设置当前角色

  // 加载该角色已有的权限
  if (staff.roleId) {
    loadRolePermissions(staff.roleId);
  } else {
    formData.permissionIds = [];
  }

  // 打开弹窗
  dialogVisible.value = true;
};

// 声明el-tree的ref引用
const permissionTree = ref(null);

// 加载角色对应的权限
const loadRolePermissions = async (roleId) => {
  if (!roleId) {
    formData.permissionIds = [];
    checkedKeys.value = []; // 同步清空
    // 手动清空树的选中状态
    permissionTree.value?.setCheckedKeys([]);
    return;
  }

  try {
    // 获取该角色已有的权限ID
    const permissionIds = await getRolePermissions(roleId);
    formData.permissionIds = permissionIds;
    // 1. 更新树的选中状态
    permissionTree.value?.setCheckedKeys(permissionIds);
    // 2. 同步更新 checkedKeys（关键）
    checkedKeys.value = [...permissionIds];
  } catch (error) {
    console.error('加载角色权限失败:', error);
    formData.permissionIds = [];
    checkedKeys.value = []; // 同步清空
    permissionTree.value?.setCheckedKeys([]);
  }
};

// 处理树形结构的勾选变化
const handleCheckChange = (data, checked, indeterminate) => {
  // 获取树当前所有选中的节点ID
  const currentCheckedKeys = permissionTree.value?.getCheckedKeys() || [];
  // 同步到 formData 和 checkedKeys
  formData.permissionIds = currentCheckedKeys;
  checkedKeys.value = [...currentCheckedKeys];
};

// 保存权限设置
const savePermissionSetting = async () => {
  if (!formData.roleId) {
    ElMessage.warning('请选择角色');
    return;
  }



  if (!formData.permissionIds.length) {
    ElMessageBox.confirm(
        '未选择任何权限，确定要保存吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(async () => {
      await saveSetting();
    });
    return;
  }

  await saveSetting();
};

// 实际保存逻辑
const saveSetting = async () => {
  try {
    const data = {
      staffId: formData.staffId,
      roleId: formData.roleId,
      permissionIds: formData.permissionIds
    };

    // 先保存员工角色关联
    const success = await saveRole(data);
    if (success) {
      // 再保存角色权限关联
      await modifyPermissionByRoleId(data.roleId, data.permissionIds);
      ElMessage.success('保存成功');

      // 更新当前员工的角色显示
      if (currentStaff.value) {
        const role = roleList.value.find(r => r.id === formData.roleId);
        if (role) {
          currentStaff.value.role.roleName = role.roleName;
          // 刷新当前行显示
          staffList.value = [...staffList.value];
        }
      }

      dialogVisible.value = false;
    }
  } catch (error) {
    ElMessage.error('保存失败');
    console.error(error);
  }
};

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false;
  // 重置表单
  formData.staffId = null;
  formData.roleId = null;
  formData.permissionIds = [];
  currentStaff.value = null;
  // 强制清空树的选中状态
  permissionTree.value?.setCheckedKeys([]);
};
</script>

<style scoped>
.role-with-permit-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  min-height: calc(100vh - 40px);
}

.search-bar {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 280px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.permission-dialog-content {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}

.permission-tree {
  margin-top: 8px;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 10px;
}

.empty-state {
  margin-top: 10px;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-input {
    width: 100%;
  }

  .permission-tree {
    width: 100%;
  }
}
</style>